package com.styytech.dadabao.ui.my;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.CommonResult;
import com.styytech.dadabao.api.requestresult.ZfbResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.bean.ZfbItem;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;
import com.styytech.dadabao.widge.zfb.PayDemo;

/**
 * Created by user on 2015/8/25.
 */
@ContentView(R.layout.activity_recharge)
public class RechargeActivity extends BaseActivity {
    @ViewInject(R.id.edt_buy)
    private EditText edt_buy;

    @ViewInject(R.id.btn_buy)
    private Button btn_buy;
    @ViewInject(R.id.llyt_main)
    private LinearLayout llyt_main;
    private CustomLoadingDialog bankdlg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    private void initViews() {
        setTopBar("充值", View.VISIBLE, View.VISIBLE, "返回");
        llyt_main.setVisibility(View.GONE);
        setView(View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");
        String url = ConstantsServerUrl.getcheckChargeUrl();
        RequestParams params = new RequestParams();
        CommonResult logResult = new CommonResult(responseResult);
        try {
            new HttpRequest(this).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
        edt_buy.addTextChangedListener(new NumWatcher(edt_buy));
        btn_buy.setBackgroundColor(Color.parseColor("#CDC9C9"));
        btn_buy.setClickable(false);
    }

    /**
     * 获取当前是否可以充值
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            Log.e("asd", "object---" + object);
            llyt_main.setVisibility(View.VISIBLE);
            setView(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");

        }

        @Override
        public void executeError(String message, int errorCode) {
            finish();
            CommonUtils.showToastMsg(RechargeActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            finish();
            CommonUtils.showToastMsg(RechargeActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
        }
    };

    @OnClick({R.id.btn_buy})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_buy:
               /* 易宝支付
                Intent intent = new Intent();
                intent.setClass(this, RechargeWebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putDouble("amount",Double.parseDouble(edt_buy.getText().toString()));
                intent.putExtras(bundle);
                startActivity(intent);
                this.finish();*/
                getZfb();
                break;
        }
    }

    private void getZfb() {
        bankdlg = new CustomLoadingDialog(this, "提示", "页面加载中...", false);
        bankdlg.show();
        String url = ConstantsServerUrl.getZFBUrl();
        RequestParams params = new RequestParams();
        params.put("token", SpUser.getUserToken(this));
        params.put("money", Double.parseDouble(edt_buy.getText().toString()));

        ZfbResult logResult = new ZfbResult(bankResult);
        try {
            new HttpRequest(this).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    AbstractResponseResult bankResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            Log.e("asd", "objects---" + object);
            ZfbItem zfbItem = (ZfbItem) object;
            PayDemo payDemo = new PayDemo(RechargeActivity.this, zfbItem);
            payDemo.pay();
            bankdlg.dismiss();

        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(RechargeActivity.this, "" + message);
            bankdlg.dismiss();
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(RechargeActivity.this, "" + message);
            bankdlg.dismiss();
        }
    };

    class NumWatcher implements TextWatcher {

        // 监听改变的文本框
        private EditText editText;
        private int editStart;
        private int editEnd;

        /**
         * 构造函数
         */
        public NumWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void onTextChanged(CharSequence string, int start, int before,
                                  int count) {
            String editable = editText.getText().toString();
            if (string.toString().equals(".")) {

                return;
            } else {
                if (string.toString().contains(".")) {
                    if (string.length() - 1 - string.toString().indexOf(".") > 2) {
                        string = string.toString().subSequence(0,
                                string.toString().indexOf(".") + 3);
                        editText.setText(string);
                        editText.setSelection(string.length());
                    }
                }
                if (string.toString().trim().substring(0).equals(".")) {
                    string = "0" + string;
                    editText.setText(string);
                    editText.setSelection(2);
                }

                if (string.toString().startsWith("0")
                        && string.toString().trim().length() > 1) {
                    if (!string.toString().substring(1, 2).equals(".")) {
                        editText.setText(string.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }


        }

        @Override
        public void afterTextChanged(Editable s) {
            editStart = edt_buy.getSelectionStart();
            editEnd = edt_buy.getSelectionEnd();
            if (!s.toString().equals("")) {
                if (s.toString().equals(".")) {
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    edt_buy.setText(s.toString());
                    edt_buy.setSelection(tempSelection);
                    return;
                } else {
                   // double now_money = Double.parseDouble(s.toString());
                    double now_money=Double.parseDouble(edt_buy.getText().toString());
                    if (now_money < 0.01) {
                        btn_buy.setBackgroundColor(Color.parseColor("#CDC9C9"));
                        btn_buy.setClickable(false);
                    } else {
                        btn_buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_common_selector));
                        btn_buy.setClickable(true);
                    }
                    if (now_money > 10000) {
                        Toast.makeText(RechargeActivity.this, "单次充值限额为1W哦",
                                Toast.LENGTH_SHORT).show();
                        s.delete(editStart - 1, editEnd);
                        int tempSelection = editStart;
                        edt_buy.setText(s.toString());
                        edt_buy.setSelection(tempSelection);
                    }
                }
            }else{
                btn_buy.setBackgroundColor(Color.parseColor("#CDC9C9"));
                btn_buy.setClickable(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

    }

    private void setText(TextView text, String string) {
        Log.e("dasd", "-----------" + string);
        String strings = subZeroAndDot(string);
        Log.e("dasd", "-----------" + strings);
        text.setText(strings);

    }

    //去掉小数点后多余的0
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

}
